﻿using System;
using System.IO;
using System.Text;
using FtpUploadWeb.Controllers;
using Quartz;
using Quartz.Impl;
using Quartz.Util;

namespace FtpUploadWeb.Common
{
    public class TaskManage
    {

        //创建一个作业调度池
        private static ISchedulerFactory schedf;
        private static IScheduler sched;


        public static void Start()
        {
            schedf = new StdSchedulerFactory();
            sched = schedf.GetScheduler().Result;
            sched.Start();//启动调度器
            StartTaskBackup();
            StartTaskBat();
            WriteTextLog("Start", "调度器启动");
        }

        public static void ResumeAll()
        {
            sched.Shutdown();
            Start();
            WriteTextLog("ResumeAll", "作业全部恢复");
        }

        public static void PauseAll()
        {
            sched.Shutdown();
            WriteTextLog("PauseAll", "作业全部暂停");
        }

        #region 异地备份

        public static string TimingBackupTask;

        public static string StartTaskBackup()
        {
            var tigger = sched.GetTrigger(new TriggerKey("trigger1"));
            if (null != tigger && null != tigger.Result && !tigger.Result.JobKey.Name.IsNullOrWhiteSpace())
            {
                return "作业已经启动,真正运行中!";
            }

            //创建出一个具体的作业
            IJobDetail job = JobBuilder.Create<BackupJob>().WithIdentity("BackupJob").Build();
            //创建触发器
            ITrigger trigger = TriggerBuilder.Create()
                .WithIdentity("trigger1")
                .StartNow()
                .WithCronSchedule(TimingBackupTask)//每分钟的第30秒执行 //0 0/32 19-22 * * ?
                .Build();// 0 0 02 * * ? * 每天02:00执行
            //加入作业调度池中
            sched.ScheduleJob(job, trigger).Wait();

            WriteTextLog("StartTask", "备份作业已经启动");
            return "作业启动成功!";
        }

        public static string ResumeJobBackup()
        {
            sched.ResumeJob(new JobKey("BackupJob"));
            WriteTextLog("ShutdownBat", "备份作业启动");
            return "备份作业启动";
        }

        public static string PauseJobBackup()
        {
            sched.PauseJob(new JobKey("BackupJob"));
            WriteTextLog("ShutdownBat", "备份作业暂停");
            return "备份作业暂停";
        }

        #endregion


        #region 执行bat文件

        public static string TimingBatTask;

        public static string StartTaskBat()
        {
            var tigger = sched.GetTrigger(new TriggerKey("trigger2"));
            if (null != tigger && null != tigger.Result && !tigger.Result.JobKey.Name.IsNullOrWhiteSpace())
            {
                tigger.Wait();
                return "作业已经启动,真正运行中!";
            }

            //1,创建出一个具体的作业
            IJobDetail jobBat = JobBuilder.Create<BatExecuteJob>().WithIdentity("BatExecuteJob").Build();
            //2,创建触发器
            ITrigger trigger = TriggerBuilder.Create()
                .WithIdentity("trigger2")
                .StartNow()
                .WithCronSchedule(TimingBatTask)//每分钟的第30秒执行 //0 0/32 19-22 * * ?
                .Build();// 0 0 02 * * ? * 每天02:00执行
            //3,把作业，触发器加入调度器
            sched.ScheduleJob(jobBat, trigger).Wait();

            WriteTextLog("StartTaskBat", "批处理作业已经启动");
            return "作业启动成功!";
        }

        public static string ResumeJobBat()
        {
            sched.ResumeJob(new JobKey("BatExecuteJob"));
            WriteTextLog("ShutdownBat", "批处理作业启动");
            return "批处理作业启动";
        }

        public static string PauseJobBat()
        {
            sched.PauseJob(new JobKey("BatExecuteJob"));
            WriteTextLog("ShutdownBat", "批处理作业暂停");
            return "批处理作业暂停";
        }

        #endregion


        /// <summary>  
        /// 写入日志到文本文件  
        /// </summary>  
        /// <param name="action">动作</param>  
        /// <param name="strMessage">日志内容</param>  
        /// <param name="time">时间</param>  
        public async static void WriteTextLog(string action, string strMessage)
        {
            try
            {
                var logFilePath = GetLogFile();

                StringBuilder str = new StringBuilder();
                str.Append("Time: " + DateTime.Now.ToString("yyyyMMdd HH:mm:ss") + "      Action:  " + action + "\r\n");
                str.Append("Message: " + strMessage + "\r\n");
                str.Append("-----------------------------------------------------------\r\n");
                StreamWriter sw;
                if (!System.IO.File.Exists(logFilePath))
                {
                    sw = System.IO.File.CreateText(logFilePath);
                }
                else
                {
                    sw = System.IO.File.AppendText(logFilePath);
                }

                await sw.WriteLineAsync(str.ToString());
                sw.Close();
            }
            catch
            {
                //忽略日志写入错误
            }
        }

        public static string GetLogFile()
        {
            string path = Directory.GetCurrentDirectory() + "/Log";
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
            return path + "/Log" + DateTime.Now.ToString("yyyMMdd") + ".txt";
        }
    }
}
